

from datetime import datetime
from backend_server import db, app
from itsdangerous import TimedJSONWebSignatureSerializer, BadSignature, SignatureExpired

class User(db.Model):
    __tablename__ = 'user'  # 定义表名
    """
    用户表，字段：账号，密码，邮箱
    """
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.String(80), unique=False, nullable=False)
    email = db.Column(db.String(120), unique=False, nullable=False)


    def __repr__(self):
        return f'<User {self.username}>'

    # def generate_token(self, expires_in=24 * 3600 * 7):
    def generate_token(self, expires_in=30):
    # def generate_token(self, expires_in=30):
        # app.config["SECRET_KEY"]：token 种子，生成token,其值可以是随机的， expires_in 超时时间
        serializer = TimedJSONWebSignatureSerializer(app.config["SECRET_KEY"], expires_in=expires_in)
        token_id = self.username + self.password + str(datetime.now())
        # dumps 用于反序列化（把 Python 对象转换成字符串），生成 Token
        # serializer.dumps默认返回字节码bytes，decode()转换为字符窜str
        token = serializer.dumps({"id": self.id, "token_id": token_id}).decode()
        return token

    # 方便外界进行调用，同时此方法不会用到对象中的数据 (??)
    @classmethod
    def check_token(cls, token):
        """
        检验token
        :return:User or None
        """
        serializer = TimedJSONWebSignatureSerializer(app.config["SECRET_KEY"])
        try:
            token_loads_results = serializer.loads(token)
            print(token_loads_results)
        # 如果token检验失败抛出BadSignature, 超时抛出SignatureExpired
        except (BadSignature, SignatureExpired):
            return None
        return User.query.get(token_loads_results["id"])

    # def very_password(self, password):
    #     if password == self.password:
    #         return True
    #     else:
    #         return False

# class Task(db.Model):
#     task_id = db.Column(db.Integer, primary_key=True)
#     name = db.Column(db.String(80), unique=True, nullable=False)
#
#     def __repr__(self):
#         return '<User %r>' % self.name

if __name__ == '__main__':
    # 全部删除再创建, 需要migrate进行优化（？？）
    db.drop_all()
    db.create_all()